package com.autotest.nore.controller;

import com.autotest.nore.common.exception.TokenEmptyException;
import com.autotest.nore.common.utils.PageUtils;
import com.autotest.nore.common.utils.Pager;
import com.autotest.nore.domain.TestFile;
import com.autotest.nore.dto.TestFileDTO;
import com.autotest.nore.request.QueryRequest;
import com.autotest.nore.service.TestFileService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;


@RestController
@RequestMapping("/autotest/file")
public class TestFileController {

    @Autowired
    private TestFileService testFileService;

    @PostMapping(value = "/upload", consumes = {"multipart/form-data"})
    public void uploadFile(@RequestParam("name") String fileName, @RequestParam("projectId") String projectId, @RequestParam("description") String description,
                    @RequestParam(value = "file", required=false) MultipartFile file, HttpServletRequest request) {

        HttpSession session = request.getSession(false); // 获取会话，如果不存在则返回null
        if (session == null || session.getAttribute("userName") == null) {
            throw new TokenEmptyException("用户未登录，请重新登录");
        }
        String userName = session.getAttribute("userName").toString();

        TestFile testFile = new TestFile();
        testFile.setName(fileName);
        testFile.setProjectId(projectId);
        testFile.setDescription(description);
        testFile.setUpdateUser(userName);
        testFileService.uploadFile(testFile, file);
    }

    @PostMapping(value = "/package/upload", consumes = {"multipart/form-data"})
    public String uploadPackage(@RequestParam("name") String packageName,
                           @RequestParam(value = "file", required=false) MultipartFile file) {
        return testFileService.uploadPackage(packageName, file);
    }

    @PostMapping("/delete")
    public void deleteFile(@RequestBody TestFile testFile) {
        testFileService.deleteFile(testFile.getId());
    }

    @GetMapping("/all/{projectId}")
    public List<TestFile> getAllTestFile(@PathVariable String projectId) {
        return testFileService.getAllTestFile(projectId);
    }

    @PostMapping("/list/{goPage}/{pageSize}")
    public Pager<List<TestFileDTO>> getTestFileList(@PathVariable int goPage, @PathVariable int pageSize,
                                          @RequestBody QueryRequest request) {
        Page<Object> page = PageHelper.startPage(goPage, pageSize, true);
        return PageUtils.setPageInfo(page, testFileService.getTestFileList(request));
    }
}
